<template>
  <el-form ref="formRef" :model="state.form" :rules="rules" :show-message="false" label-width="135px" v-loading="state.loading">
    <el-row :gutter='20'>
      <!-- 保存  分账 -->
      <el-col :span="24">
        <el-form-item label='可创建门店数' prop='buildStoreNum'>
          <div style="width: 150px">
            <el-input type="number" v-model='state.form.buildStoreNum'/>
          </div>
        </el-form-item>
      </el-col>
      <!-- 单笔订单收费金额 -->
      <el-col :span="24">
        <el-form-item label='单笔订单收费金额' prop='orderFeeAmount'>
          <el-input-number
              v-model.trim='state.form.orderFeeAmount'
              :precision='2'
              :step='1'
              :min='0'
              :max='30'
              placeholder='0.00'
              controls-position='right'/>
          <div style='font-size:12px;color:#999999;'>*说明：金额为0，则不收费。商家创建订单二维码后被客户确认后，如果订单设置是「商家支付」则从商家授权「免密支付」的支付宝账号收取费用，如果是「用户支付」，则从用户授权「免密支付」的支付宝账号收取费用。*</div>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label='分账设置'>
          <x-account v-model="state.form.orderedAccounts"></x-account>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label='是否开启主动支付' prop='activePaymentSwitch'>
          <el-switch
              v-model='state.form.activePaymentSwitch'
              active-value='1'
              inactive-value='0'
              active-text='是'
              inactive-text='否'
              active-color='#409EFF'
          />
          <div style='font-size:12px;color:#999999;'>*费用收到我司的支付宝账号，再做分账，一笔订单支持最多5个分账方。*</div>
        </el-form-item>
      </el-col>
      <!-- 主动支付抽成 -->
      <el-col :span="24" v-if="state.form.activePaymentSwitch == 1">
        <el-form-item label='主动支付抽成' prop='payDrawProportion'>
          <el-input-number
              v-model.trim='state.form.payDrawProportion'
              :precision='2'
              :step='1'
              :min='0.01'
              :max='30'
              placeholder='0'
              controls-position='right'
          >
            <template #suffix>
              <span>%</span>
            </template>
          </el-input-number>
          <div style='font-size:12px;color:#999999;'>*用户主动支付每月租金或者分期费用、临时费用场景下收取。*</div>
        </el-form-item>
      </el-col>
      <el-col :span="24" v-if="state.form.activePaymentSwitch == 1">
        <el-form-item label='分账设置'>
          <x-account v-model="state.form.proactivePaymentAccounts"></x-account>
        </el-form-item>
      </el-col>

      <el-col :span="24">
        <el-form-item label='是否开启代扣' prop='withholdSwitch'>
          <el-switch
              v-model='state.form.withholdSwitch'
              active-value='1'
              inactive-value='0'
              active-text='是'
              inactive-text='否'
              active-color='#409EFF'/>
          <div style='font-size:12px;color:#999999;'>*费用收到我司的支付宝账号，再做分账，一笔订单支持最多5个分账方。*</div>
        </el-form-item>
      </el-col>
      <!-- 系统代扣抽成 -->
      <el-col :span=24 v-if="state.form.withholdSwitch == 1">
        <el-form-item label='系统代扣抽成' prop='withholdDrawProportion'>
          <el-input-number
              v-model.trim='state.form.withholdDrawProportion'
              :precision='2'
              :step='1'
              :min='0.01'
              :max='30'
              placeholder='0'
              controls-position='right'
          >
            <template #suffix>
              <span>%</span>
            </template>
          </el-input-number>
          <div style='font-size:12px;color:#999999;'>*账单逾期，商家发起代扣，由系统执行的场景下收取。*</div>
        </el-form-item>
      </el-col>
      <el-col :span="24" v-if="state.form.withholdSwitch == 1">
        <el-form-item label='分账设置'>
          <x-account v-model="state.form.withholdAccounts"></x-account>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script setup name="company-form">
import XAccount from './components/Account';
import useStore from '@/stores/modules/platform/company';
const store = useStore();
import {defineExpose} from "vue";

const template = [{alipayAccount: "", alipayName: "", independentAccountProportion: "0",effectiveBeginTime: "", effectiveEndTime: ""}];
const state = reactive({
  loading: false,
  statusType: [{label: "正常", value: "0"},{label:"冻结", value: "9"}],
  form:{
    companyId: '',
    tenantId: '',
    configId: '',
    orderFeeAmount: '',
    buildStoreNum: '',
    activePaymentSwitch: '1',
    payDrawProportion: '',
    withholdSwitch: "1",
    withholdDrawProportion: '',
    orderedAccounts: [],
    proactivePaymentAccounts: [],
    withholdAccounts: [],
  }
});

const rules = ref({
  buildStoreNum: [{ required: true, message: '请设置可创建门店数量', trigger: 'blur' }],
  orderFeeAmount: [{ required: true, message: '请设置单位订单收费金额', trigger: 'blur' }]
});

const formRef = ref(null);
/**
 * 表单验证
 * @param callback
 * @returns {Promise<void>}
 */
const doValidate = async (callback) => {
  await formRef.value.validate((valid, fields) => {
    if (! valid) {
      let errMsg = Helper.getFirstMessage(fields);
      if (errMsg) {
        Msg.error(errMsg)
      }
      callback(false)
      return
    }

    let orderedAccounts = validateAccounts(state.form.orderedAccounts);
    if(! orderedAccounts) {
      callback(false);
      return;
    }


    let proactivePaymentAccounts = validateAccounts(state.form.proactivePaymentAccounts);
    if(! proactivePaymentAccounts) {
      callback(false);
      return;
    }

    let withholdAccounts = validateAccounts(state.form.withholdAccounts);
    if(! withholdAccounts) {
      callback(false);
      return;
    }

    let form = window.JSON.parse(window.JSON.stringify(state.form));
    form.orderedAccounts = orderedAccounts;
    form.proactivePaymentAccounts = proactivePaymentAccounts;
    form.withholdAccounts = withholdAccounts;
    callback(form)
  })
}

const validateAccounts = (accounts) => {
  let result = [];
  if(Helper.emptyArray(accounts)) {
    return result;
  }

  //alipayAccount: "", alipayName: "", independentAccountProportion: "0.00" v.effectiveBeginTime, v.effectiveEndTime
  for (let i=0;i<accounts.length; i++) {
    let account = accounts[i];
    if(Helper.empty(account.alipayAccount)) {
      continue;
    }

    if(Helper.empty(account.alipayName)) {
      Msg.error("请设置支付宝名称");
      return false;
    }

    if(Helper.empty(account.independentAccountProportion)) {
      Msg.error("请设置分账比例");
      return false;
    }

    if(Helper.empty(account.effectiveBeginTime)) {
      Msg.error("请设置支付宝有效期");
      return false;
    }

    if(Helper.empty(account.effectiveEndTime)) {
      Msg.error("请设置支付宝有效期");
      return false;
    }

    result.push(account)
  }

  return result;
}

/**
 * 保存
 * @returns {Promise<void>}
 */
const submit = async () => {
  await doValidate(async (form) => {
    if (form == false) {
      return
    }

    let result =  await store.saveConfig(form)
    if (result) {
      Dialog.close()
    }
  })
}


/**
 * 获取数据
 * @param data
 */
const render = (data, disabled) => {

  state.disabled = disabled;
  if(Helper.emptyJson(data)) {
    return
  }

  if(Helper.emptyArray(data.orderedAccounts)) {
    data.orderedAccounts = window.JSON.parse(window.JSON.stringify(template));
  }

  if(Helper.emptyArray(data.proactivePaymentAccounts)) {
    data.proactivePaymentAccounts = window.JSON.parse(window.JSON.stringify(template));
  }

  if(Helper.emptyArray(data.withholdAccounts)) {
    data.withholdAccounts = window.JSON.parse(window.JSON.stringify(template));
  }

  state.form = Object.assign(state.form, data);
}

defineExpose({render, submit})

</script>

<style scoped>

</style>
